<template>
  <div class="channelConfig">
    <div class="teamConfigBtn flex flex-horizontal-end">
      <p class="tips" v-if="showTips">
        <Icon type="md-information-circle" />
        <span>有新的线索渠道可关联，关联后您可以在“案场线索”中，查看由对应渠道所推送的线索客户 <span class="link-btn"
            @click="relationClueOnce">立即关联</span></span>
      </p>
      <Button @click="fitClassHandle" type="primary" v-if="unlocking('0102010406')"
        style="margin-right:20px;">合成班打法配置</Button>
      <Button type="primary" @click="relationClue" v-if="unlocking('0102010405')"
        style="margin-right:20px;">合并渠道</Button>
      <Button type="primary" @click="addChannel" v-if="unlocking('0102010401')">新增配置</Button>
    </div>
    <dt-grid ref="table" :page="{rows:10}" :onFetch='onFetch' />

    <!--新增配置-->
    <dt-modal-edit ref="edit" :width='800' title="客户渠道" @ok="onOk" :label-width="140">
    </dt-modal-edit>

    <!--查看配置-->
    <dt-modal-info ref="info" title="客户渠道" :label-width="140"></dt-modal-info>

    <!--关联线索渠道-->
    <channel-page ref="channelPage" @onSearch="searchFun"></channel-page>
    <!-- 合成班打法配置 -->
    <fit-class-deploy ref="fitClassDeploy" />
  </div>
</template>
<script>
  import channelMgr from '@/biz/channel/channel'
  import createOpt from './components/create'
  import channelColumn from './components/column'
  import channelPage from './components/channelPage.vue'
  import fitClassDeploy from './components/fitClassDeploy.vue'
  export default {
    data() {
      return {
        channelRelated: {
          buildingId: this.$dt.buildInfo().housesId,
          channelType: '3', //渠道类型
          channelName: '', //渠道名字
          cooperationType: '', //合作类型
          cooperationStartDate: '', //合作时间
          cooperationEndDate: '',
          channelCostType: '', //渠道费用类型
          channelCostValue: null, //渠道费用
          oaProcurement: '', //营销清单
          validate: 1,
          remarks: '', //备注
          planIdArr: [], //自获客打法
          planId: null,
          isTakeLook: '', //是否渠道带看
          isNetAcquire: '', //是否网络获客
          channelAnnex: '[]',

        },
        operateType: 0, // 0 新增 1修改 2 查看
        showTips: false,
        timer: null,
        planChannelChannelData: [],
        planChannelChannelDataArr: []
      }
    },
    components: {
      channelPage,
      fitClassDeploy
    },
    methods: {
      resolveArrFun(data, keys = []) {
        //keys可以传一个数组
        var c = []
        var d = {}
        for (var element of data) {
          let element_keyStr = ''
          let element_key = []
          let element_keyObj = {}
          for (var key of keys) {
            // console.log(element[key], element, '111');
            element_key.push(element[key])
            element_keyObj[key] = element[key]
            element_keyObj['value'] = element['customerSource']
          }
          element_keyStr = element_key.join('_')
          if (!d[element_keyStr]) {
            c.push({
              ...element_keyObj,
              children: [element],
            })
            d[element_keyStr] = element
          } else {
            for (var ele of c) {
              let isTrue = keys.some((key) => {
                return ele[key] != element[key]
              })
              if (!isTrue) {
                ele.children.push(element)
              }
            }
          }
        }
        console.log(c, 'ccccccccccccccccccc');
        return c

      },
      getPlanChannelChannelList() {

        let params = {
          buildingId: this.$dt.buildInfo().housesId
        }
        return channelMgr
          .planChannelChannelList(params)
          .then((res) => {

            // res.forEach(item => {
            //   item.key = item.planId
            //   item.value = item.planName
            // })
            this.planChannelChannelData = this.$tool.deepClone(res)

            this.planChannelChannelData.forEach(item => {
              item.key = item.planId
              item.value = item.planName
            })


            res.forEach(item => {
              item.value = item.planId
              item.label = item.planName
            })

            this.planChannelChannelDataArr = this.resolveArrFun(res,
              ['customerSourceName'])
            this.planChannelChannelDataArr.forEach(item => {
              item.label = item.customerSourceName
            })

            console.log(this.planChannelChannelData, this.planChannelChannelDataArr,
              'planChannelChannelData111111111');


          })
      },
      fitClassHandle() {
        this.$refs.fitClassDeploy.show()
      },
      showTipsFun() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId
        }
        channelMgr
          .isShowRelationTip(params)
          .then((res) => {
            this.showTips = res
          })
      },
      compareDate(date1, date2) {
        let oDate1 = new Date(date1)
        let oDate2 = new Date(date2)
        if (oDate1.getTime() <= oDate2.getTime()) {
          return true
        } else {
          return false
        }
      },
      relationClueOnce() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId
        }
        channelMgr
          .atOnceRelationFun(params)
          .then((res) => {
            this.showTips = false
            this.$refs.channelPage.show()
          })
      },
      relationClue() {
        this.$refs.channelPage.show()
      },
      searchFun() {
        // this.showTipsFun()
        this.$refs.table.fetch()
      },
      //案场渠道列表
      onFetch(data) {
        data.buildingId = this.$dt.buildInfo().housesId
        return channelMgr
          .caseChannelList(data)
          .then((res) => {
            return res
          })
      },
      addChannel() {
        this.operateType = 0
        this.channelRelated = {
          buildingId: this.$dt.buildInfo().housesId,
          channelType: '3', //渠道类型
          channelName: '', //渠道名字
          cooperationType: '', //合作类型
          cooperationStartDate: '', //合作时间
          cooperationEndDate: '',
          channelCostType: '', //渠道费用类型
          channelCostValue: null, //渠道费用
          oaProcurement: '', //营销清单
          validate: 1,
          remarks: '', //备注
          planIdArr: [], //自获客打法
          planId: null,
          isTakeLook: '', //是否渠道带看
          isNetAcquire: '', //是否网络获客
          channelAnnex: '[]',

        }
        this.$refs.edit.show(createOpt.options(this), this.channelRelated)
      },
      viewChannel(row) {
        this.operateType = 2
        // this.channelRelated = { ...row }
        this.channelRelated = Object.assign(this.channelRelated, row);
        this.planChannelChannelData.forEach(item => {
          if (item.planId == this.channelRelated.planId) {
            console.log(item, 'item');
            this.channelRelated.planIdArr = [String(item.customerSource), String(row
              .planId)]
          }
        })
        this.$refs.info.show(createOpt.options(this), this.channelRelated)
      },
      //渠道编辑
      editChannel(row) {
        // console.log(row, '我是编辑');
        // row

        //  = { ...row }

        this.channelRelated = Object.assign(this.channelRelated, row);

        // this.channelRelated.planIdArr = []
        console.log(this.channelRelated, row, '我是编辑');
        let currentItem = this.planChannelChannelData.find(item => {
          return item.planId == this.channelRelated.planId
        })
        if (currentItem) {
          this.channelRelated.planIdArr = [String(currentItem.customerSource), String(row
            .planId)]
        } else {
          this.channelRelated.planIdArr = []
        }

        // this.planChannelChannelData.forEach(item => {
        //   if (item.planId == this.channelRelated.planId) {
        //     console.log(item, 'item');
        //     this.channelRelated.planIdArr = [String(item.customerSource), String(row
        //       .planId)]
        //   }
        // })

        this.operateType = 1

        console.log(this.channelRelated, 'this.channelRelated吧那你女女女女女女女女女女女女');


        this.$refs.edit.show(createOpt.options(this), this.channelRelated)
      },
      onOk() {
        // 渠道分类2,3  合作类型
        // if ((this.channelRelated.channelType == 2 || this.channelRelated.channelType == 3) &&
        //   this.channelRelated.cooperationStartDate != '' &&
        //   this.channelRelated.cooperationStartDate != null && this.channelRelated
        //   .cooperationEndDate != '' && this.channelRelated
        //   .cooperationEndDate != null) {
        //   if (!this.compareDate(this.channelRelated.cooperationStartDate, this.channelRelated
        //       .cooperationEndDate)) {
        //     this.$Message.warning('开始日期不能大于结束日期。')
        //     return false
        //   }
        // }
        if (this.channelRelated.cooperationStartDate && this.channelRelated
          .cooperationEndDate) {
          if (!this.compareDate(this.channelRelated.cooperationStartDate, this.channelRelated
              .cooperationEndDate)) {
            this.$Message.warning('开始日期不能大于结束日期。')
            return false
          }
        }

        this.channelRelated.unit = this.channelRelated.channelCostType == 1 ? '元' : '%' //单位
        // if (this.channelRelated.channelType == 1 || this.channelRelated.channelType == 4) {
        //   this.channelRelated.cooperationType = ''
        // }
        if (this.channelRelated.channelCostType == '3') {
          this.channelRelated.channelCostValue = null
        }
        this.channelRelated.planId = this.channelRelated.planIdArr.length > 1 ? this
          .channelRelated.planIdArr[1] : null

        if (this.operateType == 0) {
          channelMgr.caseChannelInsert(this.channelRelated).then((res) => {
            this.$Message.success('渠道新增成功。')
            this.$refs.edit.hide()
            this.$refs.table.fetch()
          })
        } else {
          channelMgr.caseChannelUpdate(this.channelRelated).then((res) => {
            this.$Message.success('渠道更新成功。')
            this.$refs.edit.hide()
            this.$refs.table.fetch()
          })
        }
      },
      delChannel(row) {
        this.$Modal.confirm({
          title: '提示',
          content: '<p> 是否该渠道删除？</p>',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            let params = {
              channelId: row.channelId,
            }
            channelMgr.caseChannelDelete(params).then((res) => {
              this.$refs.table.fetch()
              this.$Message.success('删除成功。')
            })
          },
        })
      },
    },
    created() {

    },
    mounted() {
      this.getPlanChannelChannelList().then(res => {
        this.$refs.table.init(this, new channelColumn(this))
        this.$refs.table.fetch()
      })
    },
    beforeDestroy() {

    }
  }
</script>
<style lang="scss" scoped>
  .channelConfig {
    .teamConfigBtn {
      margin: 20px 0;

      .tips {
        margin-right: 20px;
        padding: 5px 10px;
        font-size: 14px;
        background: #FEFCEE;
        border-radius: 5px;

        .ivu-icon {
          margin-right: 10px;
          color: #2298ff;
          font-size: 18px;
        }

        .link-btn {
          margin-left: 10px;
          cursor: pointer;
          color: #2298ff;
        }
      }
    }
  }
</style>